package future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author fei
 * @date 2023/1/6 10:07
 * @description thenApply 和 handle 方法使用
 */
public class CompletableFutureAPI2Demo {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        // thenApply 用法
        // useThenApply(threadPool);
        CompletableFuture.supplyAsync(() -> {
            try{ TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println("111");
            return 1;
        }, threadPool).handle((f,e) -> {
            // 运行异常
            int byZero = 10 / 0;
            System.out.println("222");
            return f + 2;
        }).handle((f,e) -> {
            // 上一步发生异常后，进行处理
            if (e != null) {
                System.out.println("asdfasdfas");
                f = 5;
            }
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e) -> {
            if (e == null) {
                System.out.println("----计算结果：" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        threadPool.shutdown();
        System.out.println(Thread.currentThread().getName() + "---- 主线程先去忙其它任务");
    }

    private static void useThenApply(ExecutorService threadPool) {
        // thenApply 和 handle都是串行化的，就像是水煮鱼，要先买鱼，切片，加调料...
        // 要上一步完成才会去完成下一步动作
        CompletableFuture.supplyAsync(() -> {
            try{ TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println("111");
            return 1;
        }, threadPool).thenApply(f -> {
            int byZero = 10 / 0;
            System.out.println("222");
            return f + 2;
        }).thenApply(f -> {
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e) -> {
            if (e == null) {
                System.out.println("----计算结果：" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });
    }

}
